import json
import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *
from rich import print




def Custom_Message(parent_hwnd: int = 0, title: str = 'default_title', text: str = 'default_text', type: int = 0) -> int:
    """
    显示自定义消息框。

    该函数通过 ctypes 调用 Windows API 来显示一个带有自定义内容和标题的消息框。
    可以用于快速在 Windows 应用程序中创建消息提示。

    Args:
        parent_hwnd (int): 父窗口的窗口句柄。默认值为 0，表示没有父窗口。
        title (str): 消息框的标题。默认值为 'default_title'。
        text (str): 消息框的内容。默认值为 'default_text'。
        type (int): 消息框的类型，决定了消息框的样式和按钮。默认值为 0。

    Returns:
        int: 用户点击消息框按钮后返回的值，表示用户的选择。
    """
    return ctypes.windll.user32.MessageBoxW(parent_hwnd, text, title, type)




def Checkout_Has_Msedge_Process(_process_name:str="msedge.exe"):
    """检查是否存在指定名称的进程
        
        Args:
            _process_name (str): 进程名称
        
        Returns:
            bool: 如果存在指定名称的进程，则返回 True，否则返回 False
        
        Example:
            >>> CheckMsEdgeProcess('msedge.exe')
            True
        """
    _is_process_running = False
    for _proc in psutil.process_iter(['name']):
        if _proc.info['name'] == _process_name:
            _is_process_running = True
            break
    return _is_process_running




def Checkout_Debug_Mode_Activate() -> bool:
    """
    检查调试模式路径是否可用

    Returns:
        bool: 如果调试模式路径可用，则返回 True，否则返回 False

    Example:
        >>> MyEdge.CheckOutDebugModePath()
        True
    """
    url = "http://127.0.0.1:9652/json/version"
    try:
        response = requests.get(url=url)
        if response.status_code == 200:
            result = True
        else:
            result = False
    except Exception as e:
        print(f"请求调试模式路径时发生错误: {e}")
        result = False
    return result




def Close_All_Msedge_Process(_process_name: str="msedge.exe") -> bool:
    """
    关闭所有指定名称的进程

    Args:
        _process_name (str): 进程名称

    Returns:
        bool: 如果成功关闭所有指定名称的进程，则返回 True，否则返回 False

    Example:
        >>> MyEdge.CloseAllMsEdgeProcess('msedge.exe')
        True
    """
    success = True  # 初始化返回值
    for proc in psutil.process_iter(['pid', 'name']):
        if _process_name == proc.info['name']:
            try:
                proc.kill()  # 关闭进程
                print(f"Closed Microsoft Edge process with PID: {proc.info['pid']}")
            except Exception as e:
                print(f"Failed to close Microsoft Edge process with PID: {proc.info['pid']}. Error: {e}")
                success = False  # 如果关闭失败，设置返回值为 False
    return success




def Start_Debugmode_Browser():
    # 定义启动命令
    # command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 --disable-extensions "http://127.0.0.1:9652/json/version" "https://fxg.jinritemai.com/ffa/mshop/homepage/index" "https://myseller.taobao.com/home.htm/QnworkbenchHome/"'
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 --user-data-dir="D:\EdgeAutoCache" "http://127.0.0.1:9652/json/version"'
    
    # 启动新的进程
    CREATE_NEW_CONSOLE = 0x00000010
    subprocess.Popen(command, shell=True, creationflags=CREATE_NEW_CONSOLE)




def Start_Debugmode_Browser_With_Extensions():
    # 定义启动命令
    # command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 "http://127.0.0.1:9652/json/version" "https://fxg.jinritemai.com/ffa/mshop/homepage/index" "https://myseller.taobao.com/home.htm/QnworkbenchHome/"'
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port=9652 --user-data-dir="D:\EdgeAutoCache" "http://127.0.0.1:9652/json/version"'
    
    # 启动新的进程
    CREATE_NEW_CONSOLE = 0x00000010
    subprocess.Popen(command, shell=True, creationflags=CREATE_NEW_CONSOLE)




def Fast_Create_WebDriver_Wait_Action() -> typing.Tuple[WebDriver, WebDriverWait, ActionChains]:
    """快速创建 WebDriver、WebDriverWait 和 ActionChains 实例。

    Returns:
        typing.Tuple[WebDriver, WebDriverWait, ActionChains]: 返回 WebDriver、WebDriverWait 和 ActionChains 实例的元组。
    """
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9652")
    service = Service()
    driver = WebDriver(options=options, service=service)
    wait = WebDriverWait(driver=driver,timeout=10)
    actions = ActionChains(driver=driver)
    return driver,wait,actions






def Goto_CurrentActivateUrl(driver:WebDriver) -> str:
    import uiautomation
    root = uiautomation.GetRootControl()
    window_control = root.WindowControl(RegexName='.*?Microsoft.*?Edge')
    url_control = window_control.ToolBarControl(Name='应用栏').EditControl(Name='地址和搜索栏')
    current_activate_url = url_control.GetValuePattern().Value.replace("\"","%22")
    
    if driver.current_url == current_activate_url or driver.current_url[:-1] == current_activate_url:
        print(f"[yes]uiautoamtion 获取的当前激活的 url : {current_activate_url}")
        print(f"[yes]当前页面的 handle 对应的 url 是 : {driver.current_url}")
        return
    else:
        # print(f"提示 : 当前页面的 handle 对应的 url 是 : {driver.current_url}")
        for handle in driver.window_handles:
            driver.switch_to.window(window_name=handle)
            if driver.current_url == current_activate_url or driver.current_url[:-1] == current_activate_url:
                print(f"切换成功 : 退出切换,当前url是 : {driver.current_url}")
                break
            else:
                print(f"[else no]获取的当前激活的 url : {current_activate_url}")
                print(f"[else no]当前页面的 handle 对应的 url 是 : {driver.current_url}")
            




def _Find_input_element(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,label:str) -> WebElement:
    anchor_element = driver.find_elements(by=By.XPATH,value=f"//*[(self::span or self::label or self::div) and text()='{label}']")
    if len(anchor_element) == 1:
        find_xpath_path = "./parent::*//input"
        while True:
            try:
                element = anchor_element[0].find_element(by=By.XPATH,value=find_xpath_path)
                return element
            except NoSuchElementException:
                print(f"提示 : 当前层级没有找到 Input 元素,继续向上查找!")
                find_xpath_path = find_xpath_path.replace("//input","/parent::*//input")
                continue
            




def _Find_ByType_input_element(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,label:str,InputType:typing.Literal["","text","file"]="text",InputAccept:typing.Literal['',"video","mp4","image"]="",Multiple:bool=False,max_attempts:int = 5) -> WebElement:
    """该函数用于查找输入元素。
    """
    # 锚点元素必须是全局唯一的
    print(f"//*[(self::span or self::label or self::div) and text()='{label}']")
    elements = driver.find_elements(by=By.XPATH,value=f"//*[(self::span or self::label or self::div) and text()='{label}']")

    if elements.__len__() == 1:
        anchor_element = elements[0]
        find_xpath_path = f"./parent::*"
        input_xpath = "input"
        
        if InputType != "":
            input_xpath += f"[@type='{InputType}']"
        if InputAccept != "":
            input_xpath += f"[contains(@accept,'{InputAccept}')]"
        if Multiple == True:
            input_xpath += f"[@multiple]"
        
        find_xpath_path = f"./parent::*//{input_xpath}"

        attempt = 0
        while True:
            try:
                print(f"提示 : ./parent::*//{input_xpath}")
                element = anchor_element.find_element(by=By.XPATH,value=find_xpath_path)
                return element
            except NoSuchElementException:
                # print(f"提示 : 当前层级没有找到 Input 元素,继续向上查找!")
                # find_xpath_path = find_xpath_path.replace(f"//{input_xpath}",f"/parent::*//{input_xpath}")
                attempt += 1
                anchor_element = anchor_element.find_element(by=By.XPATH,value="./parent::*")
                
                if attempt >= max_attempts:
                    print(f"提示 : 尝试次数已达到最大值,退出查找!")
                    break
                else:
                    continue
    else:
        print(f"提示 : 锚点元素必须是全局唯一的!当前锚点元素个数 : {elements.__len__()}")





def GetDirectory_Picture_List(directory_path:str)->list:
    """
    获取目录下所有图片文件
    """
    picture_list = []
    for root,dirs,files in os.walk(directory_path):
        for file in files:
            if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg") or file.endswith("webp"):
                picture_list.append(pathlib.Path(os.path.join(root,file)).absolute().resolve().__str__())
    return picture_list





def GetPicture_Join_Text(picture_list:list)->str:
    """
    将图片列表转换为文本
    """
    picture_list_str = ""
    for index, picture_name in enumerate(picture_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    return picture_list_str





def GetExistsDirectory(FilterList:list)->str:
    DetailImageDirectory = ""
    for item in FilterList:
        if pathlib.Path(item).absolute().resolve().exists():
            DetailImageDirectory = pathlib.Path(item).absolute().resolve()
            break
    return DetailImageDirectory





def Find_MainImageTitle(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Picture_Path:str,Delay:float=5):
    """根据图片路径在淘宝网搜索同款!

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        Picture_Path (str): 图片路径
    """
    driver.switch_to.new_window("tab")
    driver.get(url="https://s.taobao.com/search?")
    
    try:
        wait_element_xpath_value = f"//div[@class='image-icon-text' and text()='搜同款']"
        wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath_value)))
    except TimeoutException:
        print(f"提示 : 网页加载失败!\n已退出!")
        return 
    
    try:
        target_element_xpath_value = f"//div[@class='image-icon-text' and text()='搜同款']"
        element = wait.until(expected_conditions.visibility_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 获取元素失败!\n已退出!")
        return
    
    try:
        wait_element_xpath_value = f"//div[contains(@class,'image-search-context-wrapper-active')]//input[@type='file']"
    except TimeoutException:
        print(f"提示 : 打开上传图片对话框失败!\n已退出!")
        return

    try:
        target_element_xpath_value = f"//div[contains(@class,'image-search-context-wrapper-active')]//input[@type='file']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        element.send_keys(pathlib.Path(Picture_Path).absolute().resolve().__str__())
    except TimeoutException:
        print(f"提示 : 没有找到可以上传图片的元素控件!\n已退出!")
        return
    
    try:
        wait_element_xpath_value  = f"//div[@id='image-search-upload-button' and text()='搜索']"
        wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath_value)))
    except TimeoutException:
        print(f"提示 : 图片上传失败!\n已退出!")
        return
    
    try:
        target_element_xpath_value = f"//div[@id='image-search-upload-button' and text()='搜索']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到开始搜索同款的按钮!\n已退出!")
        return

    time.sleep(Delay)
    driver.execute_script(open(file="./js/淘宝搜同款标题辅助文件.js",mode="r",encoding="utf-8").read())
# 
# 
# 
# 
# 



















































def Goto_Select_Category(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    # 打开网站.
    driver.switch_to.new_window("tab")
    driver.get(url="https://item.upload.taobao.com/sell/ai/category.htm")
    
    # 选择类目
    # 判断页面是否加载完毕
    try:
        wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//div[text()='商品发布']")))
    except TimeoutException:
        input("提示 : 页面加载超时,无法执行自动化操作!/n输入任意键之后结束.")
        driver.quit()
        exit()





def On_SelectPage_UploadMainPicture_ByPictureNameStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,NameStr:list):
    """批量上传主图图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 判断是否处于 [以图发品] 页面
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[contains(@class,'active')]//*[text()='以图发品']")))
    except TimeoutException:
        print(f"提示 : 没有找到选择 [以图发品] 的页面!")
        return 
    
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file'][contains(@accept,'image')][@multiple]")))
        element.send_keys(NameStr)
    except TimeoutException:
        print(f"提示 : 没有在 [选择类目页面] 找到 [input] 上传图片控件!")





def On_SelectPage_UploadMainPicture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list):
    """批量上传主图图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)

    # 判断是否处于 [以图发品] 页面
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[contains(@class,'active')]//*[text()='以图发品']")))
    except TimeoutException:
        print(f"提示 : 没有找到选择 [以图发品] 的页面!")
        return 
    
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file'][contains(@accept,'image')][@multiple]")))
        element.send_keys(picture_list_str)
    except TimeoutException:
        print(f"提示 : 没有在 [选择类目页面] 找到 [input] 上传图片控件!")





def On_SelectPage_UploadMainPicture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str):
    """批量上传主图图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
            print(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)

    # 判断是否处于 [以图发品] 页面
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[contains(@class,'active')]//*[text()='以图发品']")))
    except TimeoutException:
        print(f"提示 : 没有找到选择 [以图发品] 的页面!")
        return 
    
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file'][contains(@accept,'image')][@multiple]")))
        element.send_keys(picture_list_str)
    except TimeoutException:
        print(f"提示 : 没有在 [选择类目页面] 找到 [input] 上传图片控件!")





def On_SelectPage_Goto_ByImage(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    
    # 判断当前模式
    try:
        driver.find_element(by=By.XPATH,value=f"//*[contains(@class,'active')]//*[text()='以图发品']")
        print(f"提示 : 当前正处于 [以图发品] 模式!")
        return 
    except NoSuchElementException:
        print(f"提示 : 当前不是  [以图发品] 模式!")
        element = driver.find_element(by=By.XPATH,value=f"//*[not(contains(@class,'active'))]//*[text()='以图发品']")
        try:
            element.click()
            print(f"提示 : 正在切换至 [以图发品] 模式!")
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        




def On_SelectPage_Goto_ByFind(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    
    # 判断当前模式
    try:
        driver.find_element(by=By.XPATH,value=f"//*[contains(@class,'active')]//*[text()='搜索发品']")
        print(f"提示 : 当前正处于 [搜索发品] 模式!")
        return 
    except NoSuchElementException:
        print(f"提示 : 当前不是  [搜索发品] 模式!")
        element = driver.find_element(by=By.XPATH,value=f"//*[not(contains(@class,'active'))]//*[text()='搜索发品']")
        try:
            element.click()
            print(f"提示 : 正在切换至 [搜索发品] 模式!")
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)

    # 判断是否切换完毕
    




def On_SelectPage_Select_FirstCategory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Cate_Name:str):
    """选择第一个类目

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """

    # 确保开启 [选择类目] 的容器
    try:
        
        WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='热门推荐']")))
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='选择类目']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        pass

    # 选择第一级类目
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='{Cate_Name}']")))

        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='T恤']")))
        except TimeoutException:
            print(f"提示 : 选择一级类目失败!没有出现二级类目菜单!请检查!")
        
    except TimeoutException:
        print(f"提示 : 没有找到 [{Cate_Name}] 元素!")
   


        

def On_SelectPage_Select_SecondCategory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Cate_Name:str):
    """选择第二个类目

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//ul/li[contains(@class,'cate') and @title='{Cate_Name}']//*[text()='{Cate_Name}']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[not(@disabled)]//*[text()='确认，下一步'] | //div[contains(@class,'catProp')]")))
        except TimeoutException:
            print(f"提示 : 选择二级类目失败!当前无法点击 [下一步] 按钮!请检查!")

        
    except TimeoutException:
        print(f"提示 : 没有找到 [{Cate_Name}] 元素!")





def On_SelectPage_Select_CatePro(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Cate_Name:str):
    
    # 判断是否有 [品牌] 相关锚点的元素.
    try:
        WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'catProp')]")))
    except TimeoutException:
        print(f"提示 : 没有探测到当前页面有关于 [品牌] 选择的元素!可能不需要选择品牌,因此直接跳过!")
        return
    
    # 找到触发 [品牌] 选择按钮的元素
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'catProp')]//input")))
        element.click()
        
        # 输入 [品牌名称]
        try:
            element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[@class='sell-o-select-options']//input")))
            element.send_keys(Cate_Name)
            
            # 判断是否输入了指定的 [品牌] 名称
            try:
                WebDriverWait(driver=driver,timeout=1).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//*[@class='sell-o-select-options']//input"),Cate_Name))
                
                try:
                    element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@title='{Cate_Name}']//div[text()='{Cate_Name}']")))
                    element.click()
                except TimeoutException:
                    print(f"提示 : 没有找到 {Cate_Name} 对应的品牌名!")
                
                
            except TimeoutException:
                print(f"提示 : 输入的分类名{Cate_Name}没有出现!")
            
            
        except TimeoutException:
            print(f"提示 : 品牌输入框没有找到!")
        
    except TimeoutException:
        print(f"提示 : 没有找到触发 [品牌] 输入框的元素!")





def Goto_Parameter_Input(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Delay:float=5):
    """进入到参数填写页面

    Args:
    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[not(@disabled)]//*[text()='确认，下一步']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
    except TimeoutException:
        print(f"提示 : 没有找到 [下一步] 按钮,无法进入参数填写页面!")
    finally:
        time.sleep(Delay)




def On_InputPage_InputMaterial(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,AttributeName:str,AttributeValue:typing.Union[str,list],Delay:float=0.5):
    

    # 添加面料成分
    try:
        xpath_value = f"//button/span[text()='添加材质成分']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击
        try:
            actions_element_xpath = "//input[@placeholder='请选择材质']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print(f"提示 : 点击之后没有等到需要定位的元素!")
            return 
        
    except TimeoutException:
            print(f"提示 : 没有找到 [添加材质成分] 按钮!")
            return
            
    # 打开填写面料的输入框
    try:
        xpath_value = f"//input[@placeholder='请选择材质' and @value='']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击
        try:
            actions_element_xpath = "//div[@class='options-search']//input"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print(f"提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print(f"提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 输入面料材质成分
    try:
        xpath_value = f"//div[@class='options-search']//input"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 输入操作
        element.send_keys(AttributeValue[0])
        
        # 验证输入
        try:
            actions_element_xpath = f"//div[@class='options-item']//div[text()='{AttributeValue[0]}']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print(f"提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print(f"提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 选择面料材质成分
    try:
        xpath_value = f"//div[@class='options-item']//div[text()='{AttributeValue[0]}']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)

        # 验证点击
        try:
            actions_element_xpath = f"//em[@title='{AttributeValue[0]}' and text()='{AttributeValue[0]}']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print(f"提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print(f"提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 输入面料材质成分百分比
    try:
        xpath_value = f"//input[@placeholder='输入含量' and @value='']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 输入操作
        element.send_keys(AttributeValue[1])
        
        # 验证输入
        if element.get_attribute("value") == AttributeValue[1]:
            print(f"提示 : 输入成功!")
        else:
            print(f"提示 : 输入失败!")
            return 
        
    except TimeoutException:
        print(f"提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    return
    





def On_InputPage_InputBasicParameters(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,AttributeName:str,AttributeValue:typing.Union[str,list],Delay:float=0.5):
    """填写基础参数

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """
    if AttributeName == "面料材质" or AttributeName == "面料成分" or AttributeName == "面料":
        On_InputPage_InputMaterial(driver=driver,wait=wait,actions=actions,AttributeName=AttributeName,AttributeValue=AttributeValue)
        return
    
    
    try:
        element = driver.find_element(by=By.XPATH,value=f"//*[text()='展开补充更多信息']")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except NoSuchElementException:
        pass
    
    # 触发外部的 Input 元素,使其显式显式 输入框
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'default-items-item') and .//span[text()='{AttributeName}']]//input")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 对 [内部输入框] 进行赋值输入
        try:
            element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[@class='sell-o-select-options']//input")))
            element.send_keys(AttributeValue)
            time.sleep(Delay)
            # 等待 [内部输入框] 的输入完毕,并且确认内容
            try:
                wait.until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[@class='sell-o-select-options']//input"),text_=AttributeValue))
                
                try:
                    element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@title='{AttributeValue}']/*/div[text()='{AttributeValue}']")))
                    element.click()
                except (ElementClickInterceptedException,ElementNotInteractableException):
                    driver.execute_script("arguments[0].click();",element)
                
                
            except TimeoutException:
                print(f"提示 : 输入属性值失败!请检查!")

            
        except TimeoutException:
            print(f"提示 : 没有等到可以输入的内部输入框!")
        
    except TimeoutException:
        print(f"提示 : 没有找到 {AttributeName} 对应的外部触发输入框的元素!")
    
 
        


def On_InputPage_UploadMain_1b1_Picture_ByPictureNameStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,PictureStr:str,Delay:float=5):
    """批量上传主图 1:1  图片

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        PictureStr (str): 需要上传的图片字符串路径
        Delay (float, optional):  延迟时间. Defaults to 5.
    """
    
    # 1.打开 【选择/上传图片】 的对话框
    try:
    
        # 滚动至点击目标元素
        element_xpath = "//div[@id='struct-mainImagesGroup']//div[contains(@class,'upload-text')]"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)


        # 执行点击操作
        try:
            element.click()
            print(f"提示 : 元素 {element_xpath} 点击成功!")
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            print(f"提示 : 元素 {element_xpath} 点击失败!采用 js脚本点击!")
    
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//iframe[@id='mainImagesGroup']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print (f"提示 : 已经等到【选择/上传图片】 对话框的元素!")
        except TimeoutException:
            print(f"提示 :  没有等到【选择/上传图片】 对话框的元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到打开 【选择/上传图片】 对话框的元素!")
        return
    
    # 2.切换到iframe中
    try:
        print(f"提示 : 正在等待进入 iframe!")
        # 滚动至点击目标元素
        element_xpath = "//iframe[@id='mainImagesGroup']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))

        # 执行 iframe 切换操作
        try:
            wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(locator=(By.XPATH,element_xpath)))
            print(f"提示 : iframe元素已经切换成功!")
        except TimeoutException:
            print(f"提示 : 没有等到iframe元素,无法进行 iframe 切换!")
            return
            
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//button/span[text()='本地上传']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print(f"提示 : iframe已经切换成功,已经等待锚点元素!")
        except TimeoutException:
            print(f"提示 :  iframe已经切换成功,但是没有等待锚点元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到  iframe 元素!")
        return

    # 3.打开 【上传图片】 的界面
    try:
    
        # 滚动至点击目标元素
        element_xpath = "//button/span[text()='本地上传']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)

        # 执行点击操作
        try:
            element.click()
            print(f"提示 : 元素 {element_xpath} 点击成功!")
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            print(f"提示 : 元素 {element_xpath} 点击失败!采用 js脚本点击!")
    
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//input[@type='file']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print (f"提示 : 已经等到可以上传图片的元素!")
        except TimeoutException:
            print (f"提示 :  没有等到可以上传图片的元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到打开可以上传图片的元素!")
        return

    # 4.上传图片
    try:
        # 滚动至点击目标元素
        element_xpath = "//input[@type='file']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)

        # 执行键盘操作
        try:
            element.send_keys(PictureStr)
            wait_element_xpath = "//*[contains(text(),'上传中')]"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath)))
            print(f"提示 : 写入上传操作成功,目前正在上传过程中!")
        except TimeoutException:
            print(f"提示 : 写入上传操作失败!没有等到正在上传的界面!")

        
        # 验证上传完毕之后的界面
        # try:
        #     wait_element_xpath = f"//button[@id='sucai-tu-upload']"
        #     WebDriverWait(driver=driver,timeout=30).until(expected_conditions.invisibility_of_element(element=driver.find_element(by=By.XPATH,value=wait_element_xpath)))
        #     print(f"提示 : 检测到上传完毕的界面!")
        # except TimeoutException:
        #     print(f"提示 : 上传图片文件超时,请进行检测!")
        #     return
        wait_start_time = datetime.datetime.now()
        while wait_start_time + datetime.timedelta(seconds=30) > datetime.datetime.now():
            try:
                driver.find_element(by=By.XPATH,value=f"//*[contains(text(),'个文件上传成功')]")
                print(f"提示 : 写入上传操作成功,目前已经上完完毕!")
                driver.find_element(by=By.XPATH,value=f"//button/span[text()='完成']").click()
                time.sleep(Delay)
                break
            except NoSuchElementException:
                time.sleep(Delay)


    except TimeoutException:
        print(f"提示 : 没有找到 {element_xpath} 的元素,无法进行上传图片!")
        return

    # 5.在上传完毕之后,要选择上传的图片
        # 获取所有上传图片的列表
    PictureList = PictureStr.split("\n")
    for index,picture_name in enumerate(PictureList,start=1):
        basename = pathlib.Path(picture_name).absolute().resolve().stem
        suffix = pathlib.Path(picture_name).absolute().resolve().suffix
        ImageSpaceName =  f"{basename}.jpg"
        
        try:
             element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'PicList_PicturesShow_main-show') and position() <= {PictureList.__len__()} and .//*[contains(text(),'{basename}')]]//img")))
             driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)      
             try:
                 element.click()
                 print(f"提示  : 点击图片 {ImageSpaceName} 成功!")
             except  (ElementClickInterceptedException,ElementNotInteractableException):
                  driver.execute_script("arguments[0].click();",element)
                  print(f"提示 : 点击图片 {ImageSpaceName} 失败!采用 js脚本点击!")
                  
        except TimeoutException:
            print(f"提示 : 没有找到第 {index} 张图片,该图片的文件名为 {ImageSpaceName}")
        finally:
            time.sleep(Delay)
            try:
                driver.find_element(by=By.XPATH,value=f"//span[text()='智能裁剪中']")
                time.sleep(Delay)
            except NoSuchElementException:
                pass

    driver.switch_to.default_content()
    time.sleep(Delay)




def On_InputPage_UploadMain_1b1_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index >= 5 : continue
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 2.调用复用接口进行上传主图图片
    On_InputPage_UploadMain_1b1_Picture_ByPictureNameStr(driver=driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)

    



def On_InputPage_UploadMain_1b1_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for item in pathlib.Path(picture_directory_path).rglob('*'):
        if item.is_file():
            picture_image_path = str(item)
            picture_name_list.append(picture_image_path)
    
    
    # 2.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index >= 5 : continue
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 3.调用复用接口进行上传主图图片
    On_InputPage_UploadMain_1b1_Picture_ByPictureNameStr(driver=driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)





def On_InputPage_UploadMain_3b4_Picture_ByPictureNameStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,PictureStr:str,Delay:float=5):
    """批量上传主图 3:4  图片

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        PictureStr (str): 需要上传的图片字符串路径
        Delay (float, optional):  延迟时间. Defaults to 5.
    """
    
    # 1.打开 【选择/上传图片】 的对话框
    try:
    
        # 滚动至点击目标元素
        element_xpath = "//div[@id='sell-field-threeToFourImages']//div[contains(@class,'upload-text')]"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)


        # 执行点击操作
        try:
            element.click()
            print(f"提示 : 元素 {element_xpath} 点击成功!")
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            print(f"提示 : 元素 {element_xpath} 点击失败!采用 js脚本点击!")
    
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//iframe[@id='threeToFourImages']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print (f"提示 : 已经等到【选择/上传图片】 对话框的元素!")
        except TimeoutException:
            print(f"提示 :  没有等到【选择/上传图片】 对话框的元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到打开 【选择/上传图片】 对话框的元素!")
        return
    
    # 2.切换到iframe中
    try:
    
        # 滚动至点击目标元素
        element_xpath = "//iframe[@id='threeToFourImages']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))

        # 执行 iframe 切换操作
        try:
            wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(locator=(By.XPATH,element_xpath)))
            print(f"提示 : iframe元素已经切换成功!")
        except TimeoutException:
            print(f"提示 : 没有等到iframe元素,无法进行 iframe 切换!")
            return
            
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//button/span[text()='本地上传']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print(f"提示 : iframe已经切换成功,已经等待锚点元素!")
        except TimeoutException:
            print(f"提示 :  iframe已经切换成功,但是没有等待锚点元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到  iframe 元素!")
        return

    # 3.打开 【上传图片】 的界面
    try:
    
        # 滚动至点击目标元素
        element_xpath = "//button/span[text()='本地上传']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)

        # 执行点击操作
        try:
            element.click()
            print(f"提示 : 元素 {element_xpath} 点击成功!")
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            print(f"提示 : 元素 {element_xpath} 点击失败!采用 js脚本点击!")
    
    # 验证点击后的界面
        try:
            wait_element_xpath = f"//input[@type='file']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_element_xpath)))
            print (f"提示 : 已经等到可以上传图片的元素!")
        except TimeoutException:
            print (f"提示 :  没有等到可以上传图片的元素!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到打开可以上传图片的元素!")
        return

    # 4.上传图片
    try:
        # 滚动至点击目标元素
        element_xpath = "//input[@type='file']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH, element_xpath)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)

        # 执行键盘操作
        try:
            element.send_keys(PictureStr)
            wait_element_xpath = "//*[contains(text(),'上传中')]"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath)))
            print(f"提示 : 写入上传操作成功,目前正在上传过程中!")
        except TimeoutException:
            print(f"提示 : 写入上传操作失败!没有等到正在上传的界面!")

        
        # 验证上传完毕之后的界面
        # try:
        #     wait_element_xpath = f"//button[@id='sucai-tu-upload']"
        #     WebDriverWait(driver=driver,timeout=30).until(expected_conditions.invisibility_of_element(element=driver.find_element(by=By.XPATH,value=wait_element_xpath)))
        #     print(f"提示 : 检测到上传完毕的界面!")
        # except TimeoutException:
        #     print(f"提示 : 上传图片文件超时,请进行检测!")
        #     return
        wait_start_time = datetime.datetime.now()
        while wait_start_time + datetime.timedelta(seconds=30) > datetime.datetime.now():
            try:
                driver.find_element(by=By.XPATH,value=f"//*[contains(text(),'个文件上传成功')]")
                print(f"提示 : 写入上传操作成功,目前已经上完完毕!")
                element = driver.find_element(by=By.XPATH,value=f"//button/span[text()='完成']")
                try:
                    element.click()
                except  (ElementClickInterceptedException,ElementNotInteractableException):
                    driver.execute_script("arguments[0].click();",element)
                time.sleep(Delay)
                break
            except NoSuchElementException:
                time.sleep(Delay)

    except TimeoutException:
        print(f"提示 : 没有找到 {element_xpath} 的元素,无法进行上传图片!")
        return

    # 5.在上传完毕之后,要选择上传的图片
        # 获取所有上传图片的列表
    PictureList = PictureStr.split("\n")
    for index,picture_name in enumerate(PictureList,start=1):
        basename = pathlib.Path(picture_name).absolute().resolve().stem
        suffix = pathlib.Path(picture_name).absolute().resolve().suffix
        ImageSpaceName =  f"{basename}.jpg"
        
        try:
             element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'PicList_PicturesShow_main-show') and position() <= {PictureList.__len__()} and .//*[contains(text(),'{basename}')]]//img")))
             driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)      
             try:
                 element.click()
                 print(f"提示  : 点击图片 {ImageSpaceName} 成功!")
             except  (ElementClickInterceptedException,ElementNotInteractableException):
                  driver.execute_script("arguments[0].click();",element)
                  print(f"提示 : 点击图片 {ImageSpaceName} 失败!采用 js脚本点击!")
                  
        except TimeoutException:
            print(f"提示 : 没有找到第 {index} 张图片,该图片的文件名为 {ImageSpaceName}")
        finally:
            time.sleep(Delay)
            try:
                driver.find_element(by=By.XPATH,value=f"//span[text()='智能裁剪中']")
                time.sleep(Delay)
            except NoSuchElementException:
                pass

    driver.switch_to.default_content()
    time.sleep(Delay)




def On_InputPage_UploadMain_3b4_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传详情页图片.

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        picture_name_list (list): 图片名称列表,可以是绝对路径,也可以是相对路径
        Delay (float, optional): 延迟时间. Defaults to 5.
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index >= 5 : continue
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path

    # 2.调用复用接口进行上传主图3:4图片
    On_InputPage_UploadMain_3b4_Picture_ByPictureNameStr(driver= driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)



def On_InputPage_UploadMain_3b4_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传  3:4 主图图片

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_directory_path (str): 主图图片目录
        Delay (float, optional): 延时. Defaults to 5.
    """
    # 1.获取图片列表
    picture_name_list = list()
    for item in pathlib.Path(picture_directory_path).rglob('*'):
        if item.is_file():
            picture_image_path = str(item)
            picture_name_list.append(picture_image_path)
    
    # 2.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index >= 5 : continue
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path

    # 2.调用复用接口进行上传主图3:4图片
    On_InputPage_UploadMain_3b4_Picture_ByPictureNameStr(driver= driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)


    


def On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,PictureStr:list,Delay:float=5):
    
    
    # 1.先打开上传图片对话框
    try:
        
        # 滚动至目标元素
        xpath_value = "//div[@data-type='pic']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH, xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        print(f"提示 : 正在滚动至可以打开 【详情页图片对话框】 的元素!")
        
        # 执行点击操作
        try:
            element.click()
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击后的界面
        try:
            wait_verify_xpath_path = "//div[contains(@class,'opened')]//iframe"
            wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_verify_xpath_path)))
            print (f"提示 : 【详情页图片对话框】 已打开!")
        except TimeoutException:
            print(f"提示 : 未检测到详情页的图片对话框出现!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到打开 【详情页图片对话框】 的元素!")
        return

    # 2.切换进去对话框所在的 iframe
    try:
        xpath_value = "//div[contains(@class,'opened')]//iframe"
        wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(locator=(By.XPATH,xpath_value)))
        print(f"提示 :  切换进入 【详情页图片对话框】 所在的 iframe 元素成功!")
    except TimeoutException:
        print(f"提示 : 没有找到 【详情页图片对话框】 所在的 iframe 元素选项,无法进行 iframe 切换的操作!")
        return

    # 3.进入对话框的上传界面,出现了 input[@type='file'] 元素
    try:
        
        # 滚动至目标元素
        xpath_value = "//*[text()='本地上传']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH, xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 执行点击操作
        try:
            element.click()
        except  (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        finally:
            print(f"提示 : 正在打开可以进行上传图片的页面!")

        # 验证点击后的界面
        try:
            wait_verify_xpath_path = "//div[contains(@id,'upload')]//input[@type='file' and @multiple and contains(@accept,'image')]"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,wait_verify_xpath_path)))
            print(f"提示 : 打开可以上传图片的页面成功!")
        except TimeoutException:
            print(f"提示 : 没有等到可以上传图片的页面!")
            return
            
    except TimeoutException:
        print(f"提示 : 没有找到可以打开上传图片页面的元素!")
        return

    # 4.对详情图图片进行写入上传
    try:
        
        # 滚动至目标元素
        xpath_value = f"//div[contains(@id,'upload')]//input[@type='file' and @multiple and contains(@accept,'image')]"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 执行键盘操作
        try:
            element.send_keys(PictureStr)
            # 此处要进行修改,因为上传过程中的界面进行了一个变化,要更改判断条件.
            wait_element_xpath = "//*[contains(text(),'上传中')]"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath)))
            print(f"提示 : 写入上传操作成功,目前正在上传过程中!")
        except TimeoutException:
            print(f"提示 : 写入上传操作失败!没有等到正在上传的界面!")

        # 验证上传完毕之后的界面
        # try:
        #     wait_element_xpath = f"//input[@type='file']"
        #     # WebDriverWait(driver=driver,timeout=30).until(expected_conditions.invisibility_of_element(element=driver.find_element(by=By.XPATH,value=wait_element_xpath)))
        #     time.sleep(Delay*5)
        #     # print(f"提示 : 检测到上传完毕的界面!")
            
        # except TimeoutException:
        #     print(f"提示 : 上传图片文件超时,请进行检测!")
        #     return
        wait_start_time = datetime.datetime.now()
        while wait_start_time + datetime.timedelta(seconds=30) > datetime.datetime.now():
            try:
                driver.find_element(by=By.XPATH,value=f"//*[contains(text(),'个文件上传成功')]")
                print(f"提示 : 写入上传操作成功,目前已经上完完毕!")
                driver.find_element(by=By.XPATH,value=f"//button/span[text()='完成']").click()
                time.sleep(Delay)
                break
            except NoSuchElementException:
                time.sleep(Delay)

    except TimeoutException:
        print(f"提示 : 没有找到 {xpath_value} 的元素,无法进行上传图片!")
        return

    # 5.在上传完毕之后,要选择上传的图片
        # 获取所有上传图片的列表
    PictureList = PictureStr.split("\n")
    for index,picture_name in enumerate(PictureList,start=1):
        basename = pathlib.Path(picture_name).absolute().resolve().stem
        suffix = pathlib.Path(picture_name).absolute().resolve().suffix
        ImageSpaceName =  f"{basename}.jpg"
        
        try:
             element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'PicList_PicturesShow_main-show') and position() <= {PictureList.__len__()} and .//*[contains(text(),'{basename}')]]//img")))
             driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)      
             try:
                 element.click()
                 print(f"提示  : 点击图片 {ImageSpaceName} 成功!")
             except  (ElementClickInterceptedException,ElementNotInteractableException):
                  driver.execute_script("arguments[0].click();",element)
                  print(f"提示 : 点击图片 {ImageSpaceName} 失败!采用 js脚本点击!")
                  
        except TimeoutException:
            print(f"提示 : 没有找到第 {index} 张图片,该图片的文件名为 {ImageSpaceName}")



    # 7.确认选择的图片
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//button/span[contains(text(),'确定') and contains(text(),'{PictureList.__len__()}')]")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [确定] 的元素选项!")

    driver.switch_to.default_content()
    time.sleep(Delay)



def On_InputPage_UploadDetail_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传详情页图片.

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        picture_name_list (list): 图片名称列表,可以是绝对路径,也可以是相对路径
        Delay (float, optional): 延迟时间. Defaults to 5.
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 2.调用复用接口进行上传详情页图片
    On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver= driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)
    

    
    

def On_InputPage_UploadDetail_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传详情页图片.

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait):  WebDriverWait 实例
        actions (ActionChains):  ActionChains 实例
        picture_directory_path (str): 详情页图片所在目录路径,可以是绝对路径,也可以是相对路径
        Delay (float, optional): 延迟时间. Defaults to 5.
    """
    # 1.获取图片列表
    picture_name_list = list()
    for item in pathlib.Path(picture_directory_path).rglob('*'):
        if item.is_file():
            picture_image_path = str(item)
            picture_name_list.append(picture_image_path)
    
    # 2.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    
    # 3.调用复用接口进行上传详情页图片
    On_InputPage_UploadDetail_Picture_ByPictureNameStr(driver= driver,wait=wait,actions=actions,PictureStr=picture_list_str,Delay=Delay)





def On_InputPage_UploadMain_Video_ByStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,VideoPath:str,Delay:float=5):
    """上传主图视频

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        video_directory_path: 主图视频所在目录
    """
    # 1.获取 主图视频 路径
    VideoPath = pathlib.Path(VideoPath).absolute().resolve().__str__()
    print(f"提示 : 主图视频路径 : {VideoPath}")
            
    # 2.打开上传主图视频的对话框窗口
    try:
        xpath_value = f"//div[@id='struct-auctionVideos']//*[text()='上传视频']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到打开 [上传视频] 对话框的元素!")
        return

    # 3.进去到 上传视频 的对话框
    try:
        xpath_value = f"//div[@role='dialog']//iframe"
        wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(locator=(By.XPATH,xpath_value)))
    except TimeoutException:
        print(f"提示 : 没有检测到 [上传视频] 对话框!")
        return 
    
    # 4.获取上传主图视频的 input 控件
    try:
        xpath_value = "//input[@type='file' and contains(@accept,',mp4')]"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element())
        element.send_keys(VideoPath)
    except TimeoutException:
        print(f"提示 : 没有找到上传主图视频的 [input] 控件元素!")
        return
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_Video_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,video_directory_path:str,Delay:float=5):
    """上传主图视频

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        video_directory_path: 主图视频所在目录
    """
    # 1.获取 主图视频 路径
    video_path = str()
    for root,dirs,files in os.walk(video_directory_path):
        for file in files:
            if file.endswith(".mp4"):
                video_path = pathlib.Path(os.path.join(root,file)).absolute().resolve().__str__()
                break
            
    # 2.上传主图视频
    On_InputPage_UploadMain_Video_ByStr(driver= driver,wait=wait,actions=actions,VideoPath=video_path,Delay=Delay)





def On_InputPage_UploadSkuPicture_And_SetSkuName(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,SkuName:str,Picture_Name:str=None,Delay:float=2):
    
    # 判断是否需要进行一个颜色新增
    try:
        element = driver.find_element(by=By.XPATH,value=f"//ul/button[not(@disabled)]")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except NoSuchElementException:
        pass
    
    
    # 1.填写颜色
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@placeholder='主色(必选)' and @value='']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        element.send_keys(SkuName)
        wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,f"//span[text()='销售属性']"))).click()
        time.sleep(Delay)
        try:
            element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//input[@placeholder='主色(必选)' and @value='{SkuName}']")))
            element.click()
        except TimeoutException:
            print(f"提示 : 没有等待输入 [颜色] 后的结果!")
        
    except TimeoutException:
        print("提示 : 没有找到 [颜色] 的 [input] 控件!")
    
    
    # 2.打开选择 SKU 图片的嵌入框,此处不做 Iframe 的切换.
    try:
        # 点击外部元素,触发  SKU 嵌入框 的打开
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@class,'sell-color-item') and .//input[@value='{SkuName}']]//div[contains(@class,'sell-color-option-image-upload')]")))
        try:
            element.click()
            
            # 等待 【图片嵌入框】 元素的显示.
            try:
                wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//iframe[@id='saleProps']")))
            except TimeoutException:
                print(f"提示 : 没有检测到选择 [SKU 图片] 的嵌入框!")

        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)

    except TimeoutException:
        print("提示 : 没有找到 [目标颜色] !")
    


    # 3.进入 【图片嵌入框】 的 iframe
    try:
        wait.until(expected_conditions.frame_to_be_available_and_switch_to_it((By.XPATH,f"//iframe[@id='saleProps']")))
    except TimeoutException:
        print(f"提示 : 没有找到 【图片嵌入框】 的iframe,无法进行一个切换!")
    
    
    # 4.打开上传图片的
    try:
        
        # 点击 【上传图片】 页面的元素
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'right-btn')]")))
        try:
            element.click()            
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
        # 对点击之后的元素进行一个验证,要求出现可以上传的 【input】 元素
        # //input[@type='file' and @multiple]
        try:
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file' and @multiple]")))
        except TimeoutException:
            print(f"提示 : 没有找到可以上传图片的 [input] 元素!")

    except TimeoutException:
        print(f"提示 : 没有找到可以打开 【上传图片】 的页面元素!")

    # 5.上传 【sku图片】
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file' and @multiple]")))
        element.send_keys(pathlib.Path(Picture_Name).absolute().resolve().__str__())
    except TimeoutException:
        print(f"提示 : 没有找到可以上传图片的 [input] 元素!")
    finally:
        time.sleep(Delay)

    # 6.退出 【嵌入框】 的 iframe ,返回主框架
    driver.switch_to.default_content()





def On_InputPage_SelectSizeChat(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,SizeCharType:str,SizeCharList:list):
    """选择尺码类型以及尺码

    Args:
        driver (WebDriver): _description_
        wait (WebDriverWait): _description_
        actions (ActionChains): _description_
        SizeCharType (str): 尺码类型
        SizeCharList (list): 尺码列表
    """
    # 1.打开尺码表选择框
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//input[@placeholder='请选择尺码']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
            try:
                element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//ul/li/span[text()='{SizeCharType}' and @title='{SizeCharType}']")))
                element.click()
            except:
                print(f"提示 : 打开 [尺码表] 选择框失败!")
            
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)            
    except TimeoutException:
        print(f"提示 : 没有找到选择 [尺码表] 输入框!")

    # 2.选择尺码
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//ul/li/span[text()='{SizeCharType}' and @title='{SizeCharType}']"))) 
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)        
    except TimeoutException:
        print(f"提示 : 没有找到选择 [尺码类型] 的选项!")
    
    
    # 3.选择尺码列表
    for sizechar in SizeCharList:
        try:
            element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//label[.//input[@type='checkbox'] and .//span[text()='{sizechar}']]//input[@type='checkbox']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)        
        except TimeoutException:
            print(f"提示 : 没有找打 {sizechar} 尺码,不做选择!直接跳过当前尺码!")


    # 4.确认尺码返回
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//button/span[text()='确定']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [确定] 按钮!")


    # 5.等待是否可能出现的弹窗
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@class,'dialog')]/button/span[text()='确定']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
    except TimeoutException:
        print(f"提示 : 没有找到 [尺码表] 选择框!")





def On_InputPage_Input_Batch_Price_And_Code(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Number:int,Price:float,Product_Code):
    """批量设置价格.
    """
    
    # 1.定位到设置 价格 库存 编码的位置
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//button/span[text()='更多批量']")))
        
        # 打开填充的 【对话框】
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
        # 验证是否出现 【对话框】
        try:
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@role='dialog']/div[text()='批量填充']")))
        except TimeoutException:
            print(f"提示 : 没有在规定的时间内检测到 【批量填充】 的对话框!")
        
    except TimeoutException:
        print(f"提示 : 没有找到 [价格] 输入框元素!")

    # 2.设置价格
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='价格'] and .//input[@id='skuPrice']]//input[@id='skuPrice']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Price)
        
        try:
            wait.until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='价格'] and .//input[@id='skuPrice']]//input[@id='skuPrice']"),text_=str(Price)))
        except TimeoutException:
            print(f"提示 : 检测到 【价格】 输入框值未更新!")
    except TimeoutException:
        print(f"提示 : 没有找到 【价格】 输入框元素!")
    
    # 3.设置库存
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='数量'] and .//input[@id='skuStock']]//input[@id='skuStock']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Number)
        
        try:
            wait.until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='数量'] and .//input[@id='skuStock']]//input[@id='skuStock']"),text_=str(Number)))
        except TimeoutException:
            print(f"提示 : 检测到 【库存】 输入框值未更新!")
    except TimeoutException:
        print(f"提示 : 没有找到 【库存】 输入框元素!")
        
    # 4.设置编码
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='商家编码'] and .//input[@id='skuOuterId']]//input[@id='skuOuterId']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Product_Code)
        
        try:
            wait.until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='商家编码'] and .//input[@id='skuOuterId']]//input[@id='skuOuterId']"),text_=str(Product_Code)))
        except TimeoutException:
            print(f"提示 : 检测到 【商家编码】 输入框值未更新!")
    except TimeoutException:
        print(f"提示 : 没有找到 【商家编码】 输入框元素!")
        
    # 5.提交填写的信息
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//button/span[text()='批量填充']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)\
        
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
    except TimeoutException:
        print(f"提示 : 没有找到 [批量填充] 的按钮元素选项!")

    # 6.填写外部的商家编码
    try:
        xpath_value = f"//div[@id='struct-outerId']//input[@value='']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Product_Code)
    except TimeoutException:
        print(f"提示: 没有找到 [商家编码] 输入框元素!")
    
    # try:
    #     element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个用户累计可购买')]")))
    #     driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
    #     while element.get_attribute("value"):
    #         element.send_keys(Keys.BACKSPACE*20)
    #     element.send_keys("3")
    # except TimeoutException:
    #     print(f"提示: 没有找到 [每个用户累计可购买] 输入框元素!")





def On_InputPage_InputOhtherParameters(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,):
    # 1.设置 48 小时发货.
    try:
        xpath_value = "//span[text()='48小时内发货']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [48小时发货] 的元素选项!")
    
    
    # 2.设置订单库存计数
    try:
        xpath_value = "//span[text()='否（付款减库存）']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [否（付款减库存）] 的元素选项!")





def On_InputPage_InputLogistics(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Logistics_Template_Name:str="系统模板-商家默认模板"):
    try:
        xpath_value = f"//label[./span[text()='使用物流配送'] and .//input]//input[@type='checkbox']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 勾选使用物流配送
        if element.get_attribute("checked") != "true":
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
                try:
                    wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
                except TimeoutException:
                    print(f"提示 : 没有检测到 [运费模板] 元素!")


        # 选择运费模板
        try:
            xpath_value = f"//div[contains(@class,'template') and .//*[text()='运费模板'] and .//input[@role='combobox']]//input[@role='combobox']"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
            
            # 打开模板选项框
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            except TimeoutException:
                print(f"提示 : 没有检测到 [{Logistics_Template_Name}] 运费模板的元素选项!")
                
            # 选择 [运费模板]
            xpath_value = f"//ul/li/div/span[text()='{Logistics_Template_Name}']"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
            
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)

        except TimeoutException:
            print(f"提示 : 没有检测到 [运费模板] 元素!")
            return


    except TimeoutException:
        print(f"提示 : 没有找到 [使用物流配送] 的元素选项!")     
    





def On_InputPage_InputService(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    
    # 1.展开服务与履约
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@id,'服务与履约')]//*[text()='展开更多']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 无法对 [服务与履约] 进行展开操作!\n可能是已经展开过了!")
    
    # 2.填写购买限制
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个订单最多购买')]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys("3")
    except TimeoutException:
        print(f"提示: 没有找到 [每个订单最多购买] 输入框元素!")
    
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个用户累计可购买')]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys("3")
    except TimeoutException:
        print(f"提示: 没有找到 [每个用户累计可购买] 输入框元素!")





def On_InputPage_SizeChatTable(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,TemplateName:str,Delay:float=2):
    
    # 打开 尺码表 对话框
    try:
        xpath_value = f"//div[@id='struct-sizeMappingV3']//button"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 执行点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击
        try:
            xpath_value = "//div[@role='dialog']"
            wait.until( expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        except TimeoutException:
            print(f"提示 : 没有等到 [尺码表] 对话框!")
        
    except TimeoutException:
        print(f"提示 : 没有找到可以打开  [尺码表] 的按钮!")
        
    
    # 关闭所有的复选框
    while driver.find_elements(by=By.XPATH,value="//div[@role='dialog']//input[@type='checkbox' and @aria-checked='true']"):
        elements = driver.find_elements(by=By.XPATH,value="//div[@role='dialog']//input[@type='checkbox' and @aria-checked='true']")
        element = elements[0]
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            print(f"提示 : 点击复选框时,出现元素被遮挡!")
            driver.execute_script("arguments[0].click();", element)

    # 勾选 [商品尺码表]
    try:
        xpath_value = f"//div[@class='main-content' and .//*[text()='商品尺寸表']]//input[@type='checkbox' and @aria-checked='false']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH, xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 打开 复选框
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();", element)
        
        # 验证是否打开
        try:
            xpath_value = f"//div[@class='main-content' and .//*[text()='商品尺寸表']]//input[@role='combobox']"
            wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))
        except TimeoutException:
            print(f"提示 : 打开 [商品尺寸表] 复选框失败,没有出现 [商品尺码表填写框]!")
            return
        
    except TimeoutException:
        print("提示 : 没有找到 [商品尺寸表] 的复选框元素!")

    # 打开 尺寸表模板 选择框
    try:
        xpath_value = f"//div[@class='main-content' and .//*[text()='商品尺寸表']]//input[@role='combobox']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))

        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        finally:
            time.sleep(Delay)

        # 验证是否打开
        try:
            xpath_value  = f"//div[contains(@class,'select-popup-item')]"
            wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        except TimeoutException:
            print(f"提示 : 打开 [模板选择框] 失败!")
            return
            
    except TimeoutException:
        print(f"打开 [商品尺寸表] 复选框失败,没有出现 [商品尺码表填写框]!")
        return
    
    # 选择 模板
    try:
        xpath_value = f"//div[contains(@class,'select-popup-item') and text()='{TemplateName}']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        finally:
            time.sleep(Delay)

    except TimeoutException:
        print(f"提示 : 没有找到指定的 [商品尺寸表] 模板!")
    
    try:
        xpath_value = f"//button//*[text()='确定']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();" ,element)
    except TimeoutException:
        print(f"提示 : 没有找到 [确定] 按钮!")
        return 
         
        



def On_HtmlPage_Scroll_To_Top(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    # 滚动到页面顶部
    driver.execute_script("window.scrollTo(0, 0);")
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='当前类目']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
    except TimeoutException:
        print("提示 : 没有找到锚点元素,无法滚动至 [网页顶部] !")









if __name__ == '__main__':
    # 切换工作目录到当前脚本所在目录
    os.chdir(pathlib.Path(__file__).parent.absolute().resolve().__str__())
    driver, wait, actions = Fast_Create_WebDriver_Wait_Action()
    Goto_CurrentActivateUrl(driver)
    
    # 读取本地 cookies
    with open('cookies.json', 'r', encoding='utf-8') as f:
        cookies = json.load(f)

    # 清空浏览器当前页面中的 Cookies
    driver.get("https://mms.pinduoduo.com/home")
    driver.delete_all_cookies()
    driver.refresh()
    
    # 添加 Cookies 到浏览器
    for cookie in cookies:
        driver.add_cookie(cookie)
    
    # 刷新页面以应用 Cookies
    driver.get("https://mms.pinduoduo.com/home")
    driver.refresh()